﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace JJY.CommonHelper
{
    public class HttpRequestService
    {
        public static string GetHtmlSourceByUrl(string strUrl)
        {
            return GetHtmlSourceByUrl(strUrl, Encoding.Default);
        }

        public static string GetHtmlSourceByUrl(string strUrl, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                WebRequest webRequest = WebRequest.Create(strUrl);

                WebResponse webResponse = webRequest.GetResponse();
                StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), encoding);
                string strTemp = "";
                while ((strTemp = streamReader.ReadLine()) != null)
                {
                    result.Append(strTemp);
                }
                streamReader.Close();
                webResponse.Close();
            }
            catch(Exception e)
            {
                return e.ToString();
                //MessageBox.Show("远程服务器连接失败", "error", MessageBoxButtons.OK);
            }
            return result.ToString();
        }

        public static string GetHtmlSourceByUrl(string strUrl, string parm)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                WebRequest webRequest = WebRequest.Create(strUrl);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = parm.Length;
                Stream outStream = webRequest.GetRequestStream();
                outStream.Write(Encoding.UTF8.GetBytes(parm), 0, parm.Length);
                outStream.Close();

                WebResponse webResponse = webRequest.GetResponse();
                StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                
                Char[] read = new Char[1];
                try
                {
                    while (streamReader.Read(read, 0, 1) > 0)
                    {
                        result.Append(read[0].ToString());
                    }
                }
                catch { }

                streamReader.Close();
                webResponse.Close();
            }
            catch(Exception e)
            {
                return e.ToString();
                //MessageBox.Show("远程服务器连接失败", "error", MessageBoxButtons.OK);
            }
            return result.ToString();
        }
    }
}
